package cn.mymall.web.controller.houtai.user;


import cn.mymall.constant.StatusConstant;
import cn.mymall.entity.Menu;
import cn.mymall.entity.User;
import cn.mymall.help.PageVo;
import cn.mymall.service.IMenuService;
import cn.mymall.service.IUserService;
import cn.mymall.support.ResultCode;
import cn.mymall.util.BaseWebUtil;
import cn.mymall.util.BeanUtil;
import cn.mymall.util.BindUtils;
import cn.mymall.util.DateUtil;
import cn.mymall.vo.menu.UserMenuVo;
import cn.mymall.vo.user.UserReqVo;
import cn.mymall.vo.user.UserResVo;
import cn.mymall.vo.user.UserVo;
import cn.mymall.web.controller.houtai.BaseHoutaiController;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.support.PropertyComparator;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liqilun
 * @since 2021-02-08
 */
@RestController
public class UserApiController extends BaseHoutaiController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IMenuService menuService;

    @RequestMapping("/api/user/list")
    public ResultCode getUserList(UserReqVo reqVo){
        if(reqVo == null){
            reqVo = new UserReqVo();
        }
        Page<User> page = new Page<User>(reqVo.getPageNo(), reqVo.getPageSize());
        QueryWrapper<User> qw = new QueryWrapper();
        if(StringUtils.isNoneBlank(reqVo.getName())){
            qw.like("username", reqVo.getName());
        }
        Page<User> ipage = userService.page(page, qw.orderByDesc("id"));
        PageVo pageVo = PageVo.getInstance(ipage);
        List<UserVo> userVoList = new ArrayList<>();
        for(User user : ipage.getRecords()){
            UserVo uv = new UserVo();
            BeanUtil.copyProperties(uv, user);
            userVoList.add(uv);
        }
        pageVo.setRecords(userVoList);
        return ResultCode.getSuccessReturn(pageVo);
    }
    @RequestMapping("/api/user/all/list")
    public ResultCode getUserList(){
        List<User> userList = userService.list(new QueryWrapper<User>().orderByAsc("id"));
        List<UserVo> userVoList = new ArrayList<>();
        BeanUtil.copyListProperties(userList, userVoList, UserVo.class);
        return ResultCode.getSuccessReturn(userVoList);
    }
    @RequestMapping("/api/user/get")
    public ResultCode<User> getUser(Integer id){
        User user = new User();
        user.setSendMobileCode(StatusConstant.N);
        if(id!=null){
            user = userService.getById(id);
        }
        return ResultCode.getSuccessReturn(user);
    }
    @RequestMapping("/api/user/saveOrUpdate")
    public ResultCode saveUser(Integer id){
        User user = new User();
        if(id!=null){
            user = userService.getById(id);
        }else {
            user.setStatus(StatusConstant.Y);
            user.setAddTime(DateUtil.getCurFullTimestamp());
        }
        BindUtils.bindData(user, BaseWebUtil.getRequestMap(BaseWebUtil.getRequest()));
        if(StringUtils.isBlank(user.getEmail())){
            return ResultCode.getFailure("请输入邮箱");
        }
        if(StringUtils.isBlank(user.getUsername())){
            return ResultCode.getFailure("请输入用户名");
        }
        if(StringUtils.isBlank(user.getMobile())){
            return ResultCode.getFailure("请输入手机号");
        }
        userService.saveOrUpdate(user);
        return ResultCode.SUCCESS;
    }

    @RequestMapping("/api/user/updateStatus")
    public ResultCode saveUser(Integer id, String status){
        User user = userService.getById(id);
        user.setStatus(status);
        userService.updateById(user);
        return ResultCode.SUCCESS;
    }

    @RequestMapping("/api/user/rights")
    public ResultCode rights() {
        UserResVo userVo = getLoginUser();
        List<Menu> menuList = menuService.getUserMenuList(userVo.getId());
        if(CollectionUtils.isEmpty(menuList)) return ResultCode.SUCCESS;
        List<UserMenuVo> resultList = new LinkedList<>();
        Map<Integer,Menu> parentMenuMap = new HashMap<>();
        for(Menu menu : menuList){
            parentMenuMap.put(menu.getId(),menu);
        }

        Map<Integer, UserMenuVo> parentMap = new HashMap<>();
        for(Menu menu : menuList){
            UserMenuVo parent = null;
            if(menu.getParentId() != null) {//子类
                if(parentMap.containsKey(menu.getParentId())){
                    parent = parentMap.get(menu.getParentId());
                }else {
                    Menu parentMenu = parentMenuMap.get(menu.getParentId());
                    if(parentMenu == null){
                        parentMenu = menuService.getById(menu.getParentId());
                    }
                    parent = new UserMenuVo();
                    parent.setId(parentMenu.getId());
                    parent.setAuthName(parentMenu.getMenuName());
                    parent.setPath(parentMenu.getMenuUrl());
                    parent.setChildren(new ArrayList<>());
                    parent.setIcon(parentMenu.getIcon());
                    parent.setSortNum(parentMenu.getSortNum()!=null?parentMenu.getSortNum():0);
                    parent.setMate(ImmutableMap.of("title",parent.getAuthName()));
                    parentMap.put(menu.getParentId(), parent);
                }
                if(!resultList.contains(parent)){
                    resultList.add(parent);
                }
                UserMenuVo child = new UserMenuVo();
                child.setId(menu.getId());
                child.setAuthName(menu.getMenuName());
                child.setPath(menu.getMenuUrl());
                child.setMate(ImmutableMap.of("title",child.getAuthName()));
                child.setChildren(new ArrayList<>());
                parent.getChildren().add(child);
            }
        }
        Collections.sort(resultList,new PropertyComparator<>("sortNum",false, true));
        return ResultCode.getSuccessReturn(resultList);
    }

}
